<template>
  <div class="koi-flex">
    <KoiSearch :isFold="false" :showSearch="showSearch">
      <!-- 搜索条件 -->
      <el-form :inline="true">
        <el-form-item label="文章标题" prop="articleTitle">
          <el-input
            placeholder="请输入文章标题"
            v-model="searchParams.articleTitle"
            clearable
            style="width: 220px"
            @keyup.enter.native="handleListPage"
          ></el-input>
        </el-form-item>
        <el-form-item label="文章类别" prop="categoryId">
          <el-select
            placeholder="请选择文章类别"
            v-model="searchParams.categoryId"
            clearable
            filterable
            style="width: 220px"
            @keyup.enter.native="handleListPage"
          >
            <el-option v-for="item in categoryOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="文章标签" prop="tagId">
          <el-select placeholder="请选择文章标签" v-model="searchParams.tagId" clearable filterable style="width: 220px">
            <el-option v-for="item in tagOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="文章类型" prop="articleType">
          <el-select
            placeholder="请选择文章类型"
            v-model="searchParams.articleType"
            clearable
            style="width: 220px"
            @keyup.enter.native="handleListPage"
          >
            <el-option
              v-for="koi in koiDicts.blog_article_type"
              :key="koi.dictValue"
              :label="koi.dictLabel"
              :value="koi.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="文章状态" prop="articleStatus">
          <el-select
            placeholder="请选择文章状态"
            v-model="searchParams.articleStatus"
            clearable
            style="width: 220px"
            @keyup.enter.native="handleListPage"
          >
            <el-option
              v-for="koi in koiDicts.sys_switch_status"
              :key="koi.dictValue"
              :label="koi.dictLabel"
              :value="koi.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="是否推荐" prop="isCommend">
          <el-select
            placeholder="请选择是否推荐"
            v-model="searchParams.isCommend"
            clearable
            style="width: 220px"
            @keyup.enter.native="handleListPage"
          >
            <el-option v-for="koi in koiDicts.sys_yes_no" :key="koi.dictValue" :label="koi.dictLabel" :value="koi.dictValue" />
          </el-select>
        </el-form-item>
        <el-form-item label="是否热门" prop="isHot">
          <el-select
            placeholder="请选择是否热门"
            v-model="searchParams.isHot"
            clearable
            style="width: 220px"
            @keyup.enter.native="handleListPage"
          >
            <el-option v-for="koi in koiDicts.sys_yes_no" :key="koi.dictValue" :label="koi.dictLabel" :value="koi.dictValue" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="search" plain @click="handleSearch" v-auth="['blog:article:search']">{{
            $t("button.search")
          }}</el-button>
          <el-button type="danger" icon="refresh" plain @click="resetSearch">{{ $t("button.reset") }}</el-button>
        </el-form-item>
      </el-form>
    </KoiSearch>  
    <KoiCard>
      <!-- 表格头部按钮 -->
      <el-row :gutter="10">
        <el-col :span="1.5" v-auth="['blog:article:add']">
          <KoiPublish type="add" @refresh="handleListPage"></KoiPublish>
        </el-col>
        <el-col :span="1.5" v-auth="['blog:article:delete']">
          <el-button type="danger" icon="delete" plain @click="handleBatchDelete()" :disabled="multiple">{{
            $t("button.delete")
          }}</el-button>
        </el-col>
        <KoiToolbar v-model:showSearch="showSearch" @refreshTable="handleListPage"></KoiToolbar>
      </el-row>

      <div class="h-20px"></div>
      <!-- 数据表格 -->
      <el-table
        v-loading="loading"
        border
        :data="tableList"
        :empty-text="$t('msg.null')"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column :label="$t('table.number')" prop="articleId" width="80px" align="center" type="index"></el-table-column>
        <el-table-column
          label="文章标题"
          prop="articleTitle"
          width="300px"
          align="center"
          :show-overflow-tooltip="true"
        ></el-table-column>
        <el-table-column label="文章图片" prop="picture" width="120px" align="center" :show-overflow-tooltip="true">
          <template #default="scope">
            <div class="flex flex-justify-center">
              <el-image
                class="max-w-100% h-52px rounded-8px"
                :src="scope.row.picture"
                fit="contain"
                :preview-teleported="true"
                :preview-src-list="[scope.row.picture]"
              >
                <!-- 这个地方若加载不出来，暂时用一个默认图片代替 -->
                <!-- https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png -->
                <template #error>
                  <el-image
                    src="https://i.postimg.cc/zBRKsrdv/carousel66.jpg"
                    fit="cover"
                    :preview-teleported="true"
                    :preview-src-list="['https://i.postimg.cc/zBRKsrdv/carousel66.jpg']"
                    class="max-w-100% h-52px rounded-8px"
                  ></el-image>
                </template>
              </el-image>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          label="文章类别"
          prop="categoryName"
          width="120px"
          align="center"
          :show-overflow-tooltip="true"
        ></el-table-column>
        <el-table-column label="文章标签" prop="tagList" width="450px" align="center" :show-overflow-tooltip="true">
          <template #default="scope">
            <div class="flex flex-justify-center gap-3px">
              <el-tag v-for="item in scope.row.tagList" :key="item.tagId" :type="getRandomTagColor()">{{ item.tagName }}</el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="文章类型" prop="articleType" width="100px" align="center">
          <template #default="scope">
            <KoiTag :tagOptions="koiDicts.blog_article_type" :value="scope.row.articleType"></KoiTag>
          </template>
        </el-table-column>
        <el-table-column label="文章状态" prop="articleStatus" width="100px" align="center">
          <template #default="scope">
            <el-switch
              v-model="scope.row.articleStatus"
              :active-text="$t('dict.sys_switch_status.open')"
              :inactive-text="$t('dict.sys_switch_status.stop')"
              active-value="0"
              inactive-value="1"
              :inline-prompt="true"
              @change="handleSwitchArticleStatus(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="是否推荐" prop="isCommend" width="100px" align="center">
          <template #default="scope">
            <el-switch
              v-model="scope.row.isCommend"
              active-text="是"
              inactive-text="否"
              active-value="0"
              inactive-value="1"
              :inline-prompt="true"
              @change="handleSwitchIsCommend(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="是否热门" prop="isHot" width="100px" align="center">
          <template #default="scope">
            <el-switch
              v-model="scope.row.isHot"
              active-text="是"
              inactive-text="否"
              active-value="0"
              inactive-value="1"
              :inline-prompt="true"
              @change="handleSwitchIsHot(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="浏览数" prop="views" width="120px" align="center" :show-overflow-tooltip="true">
          <template #default="scope">
            <div class="text-[--el-color-primary]">
              {{ getFormatToK(scope.row.views) + " Views" }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="排序" prop="sorted" width="80px" align="center" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column label="备注" prop="remark" width="300px" align="center" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column label="创建时间" prop="createTime" width="180px" align="center"></el-table-column>
        <el-table-column
          :label="$t('table.operate')"
          align="center"
          width="150"
          fixed="right"
          v-auth="['blog:article:update', 'blog:article:delete']"
        >
          <template #default="{ row }">
            <KoiPublish type="update" :articleId="row.articleId" @refresh="handleListPage"></KoiPublish>
            <el-tooltip :content="$t('button.delete')" placement="top">
              <el-button
                type="danger"
                icon="Delete"
                circle
                plain
                @click="handleDelete(row)"
                v-auth="['blog:article:delete']"
              ></el-button>
            </el-tooltip>
            <el-tooltip :content="$t('button.preview')" placement="top">
              <el-button
                type="warning"
                icon="View"
                circle
                plain
                @click="handlePreview(row)"
                v-auth="['blog:article:preview']"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <div class="h-20px"></div>
      <!-- 分页 -->
      <el-pagination
        background
        v-model:current-page="searchParams.pageNo"
        v-model:page-size="searchParams.pageSize"
        v-show="total > 0"
        :page-sizes="[10, 20, 50, 100, 200]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleListPage"
        @current-change="handleListPage"
      />

      <!-- 文章预览 -->
      <KoiDrawer ref="koiDrawerRef" :title="title" size="100%" footerHidden>
        <template #content>
          <el-row>
            <el-col :sm="18" :xs="24">
              <MdPreview
                class="!bg-[--el-fill-color-blank]"
                v-model="content"
                :editorId="editorId"
                :theme="globalStore.isDark ? 'dark' : 'light'"
                :previewTheme="globalStore.previewTheme"
                :codeTheme="globalStore.codeTheme"
              />
            </el-col>
            <el-col :sm="6" :xs="0">
              <el-card class="pos-sticky top-0px rounded-8px">
                <div class="m-b-10px">
                  <el-dropdown @command="handlePreviewCommand">
                    <el-button plain>
                      预览主题<el-icon class="el-icon--right"><arrow-down /></el-icon>
                    </el-button>
                    <template #dropdown>
                      <el-dropdown-menu>
                        <el-dropdown-item command="default" :disabled="globalStore.previewTheme == 'default'"
                          >default</el-dropdown-item
                        >
                        <el-dropdown-item command="github" :disabled="globalStore.previewTheme == 'github'"
                          >github</el-dropdown-item
                        >
                        <el-dropdown-item command="vuepress" :disabled="globalStore.previewTheme == 'vuepress'"
                          >vuepress</el-dropdown-item
                        >
                        <el-dropdown-item command="mk-cute" :disabled="globalStore.previewTheme == 'mk-cute'"
                          >mk-cute</el-dropdown-item
                        >
                        <el-dropdown-item command="smart-blue" :disabled="globalStore.previewTheme == 'smart-blue'"
                          >smart-blue</el-dropdown-item
                        >
                        <el-dropdown-item command="cyanosis" :disabled="globalStore.previewTheme == 'cyanosis'"
                          >cyanosis</el-dropdown-item
                        >
                        <el-dropdown-item command="codeTheme" :disabled="globalStore.previewTheme == 'codeTheme'"
                          >codeTheme</el-dropdown-item
                        >
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>
                  <el-dropdown class="m-l-6px" @command="handleCodeCommand">
                    <el-button plain>
                      代码主题<el-icon class="el-icon--right"><arrow-down /></el-icon>
                    </el-button>
                    <template #dropdown>
                      <el-dropdown-menu>
                        <el-dropdown-item command="atom" :disabled="globalStore.codeTheme == 'atom'">atom</el-dropdown-item>
                        <el-dropdown-item command="a11y" :disabled="globalStore.codeTheme == 'a11y'">a11y</el-dropdown-item>
                        <el-dropdown-item command="github" :disabled="globalStore.codeTheme == 'github'">github</el-dropdown-item>
                        <el-dropdown-item command="gradient" :disabled="globalStore.codeTheme == 'gradient'"
                          >gradient</el-dropdown-item
                        >
                        <el-dropdown-item command="kimbie" :disabled="globalStore.codeTheme == 'kimbie'">kimbie</el-dropdown-item>
                        <el-dropdown-item command="paraiso" :disabled="globalStore.codeTheme == 'paraiso'"
                          >paraiso</el-dropdown-item
                        >
                        <el-dropdown-item command="qtcreator" :disabled="globalStore.codeTheme == 'qtcreator'"
                          >qtcreator</el-dropdown-item
                        >
                        <el-dropdown-item command="stackoverflow" :disabled="globalStore.codeTheme == 'stackoverflow'"
                          >stackoverflow</el-dropdown-item
                        >
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>
                </div>
                <!-- 目录标题 -->
                <div class="flex flex-items-center text-18px m-b-8px font-bold text-[--el-text-color-primary] select-none">
                  <KoiSvgIcon name="koi-directory" width="23" height="23" class="m-r-6px"></KoiSvgIcon>
                  <div>文章目录</div>
                </div>
                <!-- 目录数据超过66vh进行局部滚动 -->
                <div class="overflow-y-auto max-h-66vh">
                  <MdCatalog :editorId="editorId" :scrollElement="scrollElement" :offsetTop="80" :scrollElementOffsetTop="90" />
                </div>
              </el-card>
            </el-col>
          </el-row>
        </template>
      </KoiDrawer>
    </KoiCard>
  </div>
</template>

<script setup lang="ts" name="articlePage">
import { ref, onMounted, computed } from "vue";
import { koiMsgSuccess, koiMsgError, koiMsgWarning } from "@/utils/koi.ts";
import { ElMessageBox } from "element-plus";
import { getFormatToK } from "@/utils/index.ts";
import { listCategoryElSelect } from "@/api/blog/category/index.ts";
import { listTagElSelect } from "@/api/blog/tag/index.ts";
import { listPage, deleteById, batchDelete, updateStatus, preview } from "@/api/blog/article/index.ts";
import KoiPublish from "./components/Publish.vue";
import { useI18n } from "vue-i18n";
import { useKoiDict } from "@/hooks/dicts/index.ts";
import { MdPreview, MdCatalog } from "md-editor-v3";
import "md-editor-v3/lib/style.css";
import useGlobalStore from "@/stores/modules/global.ts";

const globalStore = useGlobalStore();
const editorId = ref("KOI-MD-ARTICLE-PREVIEW-EDITOR");
const scrollElement = ref<any>();
scrollElement.value = computed(() => document.querySelector(".body"));
const { koiDicts } = useKoiDict(["blog_article_type", "sys_switch_status", "sys_yes_no"]);
const { t } = useI18n();
// 表格加载动画Loading
const loading = ref(false);
// 是否显示搜索表单[默认显示]
const showSearch = ref<boolean>(true);
// 表格数据
const tableList = ref<any>([]);

// 查询参数
const searchParams = ref<any>({
  pageNo: 1, // 第几页
  pageSize: 10, // 每页显示多少条
  articleTitle: undefined,
  categoryId: undefined,
  tagId: undefined,
  articleType: undefined,
  articleStatus: undefined,
  isCommend: undefined,
  isHot: undefined
});

const total = ref<number>(0);

/** 重置搜索参数 */
const resetSearchParams = () => {
  searchParams.value = {
    pageNo: 1,
    pageSize: 10,
    articleTitle: undefined,
    categoryId: undefined,
    tagId: undefined,
    articleType: undefined,
    articleStatus: undefined,
    isCommend: undefined,
    isHot: undefined
  };
};

/** 搜索 */
const handleSearch = () => {
  searchParams.value.pageNo = 1;
  handleTableData();
};

/** 重置 */
const resetSearch = () => {
  resetSearchParams();
  handleListPage();
};

/** 数据表格 */
const handleListPage = async () => {
  try {
    tableList.value = []; // 重置表格数据
    loading.value = true;
    const res: any = await listPage(searchParams.value);
    tableList.value = res.data.records;
    total.value = res.data.total;
    loading.value = false;
  } catch (error) {
    console.log(error);
    koiMsgError(t("msg.fail"));
  }
};

/** 数据表格[不带Loading，删除、批量删除等使用] */
const handleTableData = async () => {
  try {
    const res: any = await listPage(searchParams.value);
    tableList.value = res.data.records;
    total.value = res.data.total;
  } catch (error) {
    console.log(error);
    koiMsgError(t("msg.fail"));
  }
};

onMounted(() => {
  // 获取表格数据
  handleListPage();
  // 获取文章类别下拉框数据
  handleCategoryElSelect();
  // 获取文章标签下拉框数据
  handleTagElSelect();
});

const ids = ref<any>([]); // 选择数组
const single = ref<boolean>(true); // 非单个禁用
const multiple = ref<boolean>(true); // 非多个禁用

/** 是否多选 */
const handleSelectionChange = (selection: any) => {
  ids.value = selection.map((item: any) => item.articleId);
  single.value = selection.length != 1; // 单选
  multiple.value = !selection.length; // 多选
};

// 添加 OR 修改抽屉Ref
const koiDrawerRef = ref();
// 标题
const title = ref();

/** 删除 */
const handleDelete = (row: any) => {
  const id = row.articleId;
  if (id == null || id == "") {
    koiMsgWarning(t("msg.selectData"));
    return;
  }
  ElMessageBox.confirm(t("msg.confirmDelete"), t("msg.remind"), {
    confirmButtonText: t("button.confirm"),
    cancelButtonText: t("button.cancel"),
    type: "warning"
  })
    .then(async () => {
      try {
        await deleteById(id);
        handleTableData();
        koiMsgSuccess(t("msg.success"));
      } catch (error) {
        console.log(error);
        handleTableData();
        koiMsgError(t("msg.fail"));
      }
    })
    .catch(() => {
      koiMsgWarning(t("msg.cancelled"));
    });
};

/** 批量删除 */
const handleBatchDelete = () => {
  if (ids.value.length == 0) {
    koiMsgWarning(t("msg.selectData"));
    return;
  }
  ElMessageBox.confirm(t("msg.confirmDelete"), t("msg.remind"), {
    confirmButtonText: t("button.confirm"),
    cancelButtonText: t("button.cancel"),
    type: "warning"
  })
    .then(async () => {
      try {
        await batchDelete(ids.value);
        handleTableData();
        koiMsgSuccess(t("msg.success"));
      } catch (error) {
        console.log(error);
        handleTableData();
        koiMsgError(t("msg.fail"));
      }
    })
    .catch(() => {
      koiMsgWarning(t("msg.cancelled"));
    });
};

const colors = ["primary", "success", "info", "warning", "danger"];
/* 获取随机标签颜色 */
const getRandomTagColor = () => {
  const randomIndex = Math.floor(Math.random() * colors.length);
  return colors[randomIndex];
};

// 文章类别下拉框
const categoryOptions = ref();

/* 获取文章类别下拉框数据 */
const handleCategoryElSelect = async () => {
  try {
    categoryOptions.value = [];
    const res: any = await listCategoryElSelect();
    categoryOptions.value = res.data;
  } catch (error) {
    console.log(error);
    koiMsgError(t("msg.fail"));
  }
};

// 标签多选下拉框
const tagOptions = ref();

/** 获取文章标签下拉框数据 */
const handleTagElSelect = async () => {
  try {
    tagOptions.value = [];
    const res: any = await listTagElSelect();
    tagOptions.value = res.data;
  } catch (error) {
    console.log(error);
    koiMsgError(t("msg.fail"));
  }
};

/** 文章状态开关 */
const handleSwitchArticleStatus = (row: any) => {
  let text = row.articleStatus === "0" ? t("dict.sys_switch_status.open") : t("dict.sys_switch_status.stop");
  if (!row.articleId || !row.articleStatus) {
    row.articleStatus = row.articleStatus == "0" ? "1" : "0";
    koiMsgWarning(t("msg.selectData"));
    return;
  }
  ElMessageBox.confirm(t("msg.confirmWant") + "[" + text + "]?", t("msg.remind"), {
    confirmButtonText: t("button.confirm"),
    cancelButtonText: t("button.cancel"),
    type: "warning"
  })
    .then(async () => {
      try {
        await updateStatus(row.articleId, "articleStatus", row.articleStatus);
        koiMsgSuccess(t("msg.success"));
      } catch (error) {
        console.log(error);
        row.articleStatus = row.articleStatus == "0" ? "1" : "0";
        handleTableData();
        koiMsgError(t("msg.fail"));
      }
    })
    .catch(() => {
      row.articleStatus = row.articleStatus == "0" ? "1" : "0";
      koiMsgWarning(t("msg.cancelled"));
    });
};

/** 是否推荐开关 */
const handleSwitchIsCommend = (row: any) => {
  let text = row.isCommend === "0" ? t("dict.sys_switch_status.open") : t("dict.sys_switch_status.stop");
  if (!row.articleId || !row.isCommend) {
    row.isCommend = row.isCommend == "0" ? "1" : "0";
    koiMsgWarning(t("msg.selectData"));
    return;
  }
  ElMessageBox.confirm(t("msg.confirmWant") + "[" + text + "]?", t("msg.remind"), {
    confirmButtonText: t("button.confirm"),
    cancelButtonText: t("button.cancel"),
    type: "warning"
  })
    .then(async () => {
      try {
        await updateStatus(row.articleId, "isCommend", row.isCommend);
        koiMsgSuccess(t("msg.success"));
      } catch (error) {
        console.log(error);
        row.isCommend = row.isCommend == "0" ? "1" : "0";
        handleTableData();
        koiMsgError(t("msg.fail"));
      }
    })
    .catch(() => {
      row.isCommend = row.isCommend == "0" ? "1" : "0";
      koiMsgWarning(t("msg.cancelled"));
    });
};

/** 是否热门开关 */
const handleSwitchIsHot = (row: any) => {
  let text = row.isHot === "0" ? "启用" : "停用";
  if (!row.articleId || !row.isHot) {
    row.isHot = row.isHot == "0" ? "1" : "0";
    koiMsgWarning(t("msg.selectData"));
    return;
  }
  ElMessageBox.confirm(t("msg.confirmWant") + "[" + text + "]?", t("msg.remind"), {
    confirmButtonText: t("button.confirm"),
    cancelButtonText: t("button.cancel"),
    type: "warning"
  })
    .then(async () => {
      try {
        await updateStatus(row.articleId, "isHot", row.isHot);
        koiMsgSuccess(t("msg.success"));
      } catch (error) {
        console.log(error);
        row.isHot = row.isHot == "0" ? "1" : "0";
        handleTableData();
        koiMsgError(t("msg.fail"));
      }
    })
    .catch(() => {
      row.isHot = row.isHot == "0" ? "1" : "0";
      koiMsgWarning(t("msg.cancelled"));
    });
};

const content = ref();
/** 预览 */
const handlePreview = async (row: any) => {
  if (row.articleId == null || row.articleId == "") {
    koiMsgWarning(t("msg.selectData"));
    return;
  }
  title.value = "预览文章";
  koiDrawerRef.value.koiOpen();
  try {
    const res: any = await preview(row.articleId);
    content.value = res.data.content;
  } catch (error) {
    console.log(error);
    koiMsgError(t("msg.fail"));
  }
};

/** 预览主题 */
const handlePreviewCommand = (command: string) => {
  globalStore.setGlobalState("previewTheme", command);
};

/** 代码主题 */
const handleCodeCommand = (command: string) => {
  globalStore.setGlobalState("codeTheme", command);
};
</script>

<style lang="scss">
.md-editor-catalog-active > span {
  color: var(--el-color-primary) !important;
}
.md-editor-catalog-indicator {
  background-color: var(--el-color-primary) !important;
}
.md-editor-catalog-link span:hover {
  color: var(--el-color-primary) !important;
}
</style>
